<?php
class Pageley_Log_DailyFileAppender extends Pageley_Log_FileAppender {
	private $daysToKeep = 10;
	private $currentLogFile;
	
	const FOREVER = "forever";
	
	public function setDaysToKeep($daysToKeep) {
		if($daysToKeep < 0) {
			throw new Pageley_Util_IllegalArgumentException("DaysToKeep cannot be negative.");
		}
		$this->daysToKeep = $daysToKeep;
	}
	
	protected function getLogFile() {
		$logFile = $this->currentLogFile;
		if($logFile === null) {
			$logFile = parent::getLogFile();
			$logFilePath = $logFile->getPath();
			$logFileDirectory = $logFile->getParent();
			if(!$logFileDirectory->exists()) {
				$logFileDirectory->createDirectory();
			}
			$logFileNameWithoutExtension = $logFile->getNameWithoutExtension();
			$logFileExtension = $logFile->getExtension();
			$now = new Pageley_Util_Timestamp();
			$date = $now->format("Y-m-d");
			$system = Pageley_Util_System::getInstance();
			$logFilePath = $logFileDirectory->getPath() . "/" . $logFileNameWithoutExtension . "." . $date  . $logFileExtension;
			$logFile = new Pageley_Util_File($logFilePath);
			$this->currentLogFile = $logFile;
			if(!$logFile->exists() && $this->daysToKeep != self::FOREVER) {
				$this->cleanUpOldLogFiles();
			}
		}
		return $logFile;
	}
	
	private function cleanUpOldLogFiles() {
		$logFileDirectory = $this->currentLogFile->getParent();
		$logFileBaseName = parent::getLogFile()->getNameWithoutExtension();
		$logFileExtension = parent::getLogFile()->getExtension();
		$logFiles = new Pageley_Util_ArrayMap();
		$now = new Pageley_Util_Timestamp();
		foreach($logFileDirectory->getFiles() as $file) {
			$fileName = $file->getName();
			if(Pageley_Util_String::startsWith($fileName, $logFileBaseName) && Pageley_Util_String::endsWith($fileName, $logFileExtension)) {
				$date = $file->getLastChanged();
				if ($now->compareTo($date, Pageley_Util_Timestamp::DAYS) > $this->daysToKeep) {
					$file->delete();
				}
			}
		}
	}
}